package com.greenhouse.service.impl;

import com.greenhouse.config.Request;
import com.greenhouse.mapper.environment.EquipmentMapper;
import com.greenhouse.mapper.greenhouse.GreenhouseMapper;
import com.greenhouse.model.Equipment;
import com.greenhouse.request.EquipmentRequest;
import com.greenhouse.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EquipmentServiceImpl implements EquipmentService {
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private GreenhouseMapper greenhouseMapper;

    @Override
    public Request<List<EquipmentRequest>> selectEquipment(String name, Integer userId) {
        List<EquipmentRequest> equipmentRequests = greenhouseMapper.showGreenhouseIdAndName(userId);
        for (int i = 0; i < equipmentRequests.size(); i++) {
            List<Equipment> equipments = equipmentMapper.selectEquipments(equipmentRequests.get(i).getGreenhouseId(), name);
            equipmentRequests.get(i).setEquipments(equipments);
        }
        return Request.success("查询成功", equipmentRequests);
    }

    @Override
    public Request<Equipment> addEquipment(String name, Equipment equipment, Integer greenhouseId) {
        Integer n = equipmentMapper.insertDataToExist(name, greenhouseId, equipment.getName());
        if (n == 1) {
            return Request.success("添加成功", equipment);
        }
        return Request.error("添加失败", null);
    }

    @Override
    public Request<String> updateEquipment(String name, Integer id, String equipment) {
        Integer n = equipmentMapper.updateEquipment(name, equipment, id);
        if (n == 1) {
            return Request.success("修改成功", null);
        }
        return Request.error("修改失败", null);
    }

    @Override
    public Request<String> deleteEquipment(String equipmentTableName, Integer id) {
        Integer n = equipmentMapper.deleteEquipment(equipmentTableName, id);
        if (n > 0) {
            return Request.success("删除成功", null);
        }
        return Request.error("删除失败", null);
    }

    @Override
    public Request<String> updateEquipmentStatus(String equipmentTableName, Integer id, Integer status) {
        Integer n;
        Integer s = equipmentMapper.selectStatus(equipmentTableName, id);
        //如果状态相同，则不执行操作
        if (s == status) {
            return Request.success("状态相同，不执行操作", null);
        }
        if (status == 1) {
            //启动设备
            n = equipmentMapper.startEquipment(equipmentTableName, id);
            if (n == 1) {
                return Request.success("启动成功", null);
            }
            return Request.error("启动设备失败", null);
        } else if (status == 0) {
            //关闭设备
            n = equipmentMapper.stopEquipment(equipmentTableName, id);
            if (n == 1) {
                Equipment equipment = equipmentMapper.selectEquipment(equipmentTableName, id);
                getTime(equipment);
                n = equipmentMapper.updateRunTime(equipmentTableName, id ,equipment.getTotalRuntime());
                System.out.println(n);
                if (n == 1) {
                    return Request.success("关闭成功", null);
                }
                return Request.error("无法修改设备运行时间", null);
            }
            return Request.error("关闭设备失败", null);
        }
        return Request.error("修改状态失败", null);

    }


    public void getTime(Equipment equipment) {
        // 计算时间差（以毫秒为单位）
        long timeDifference = equipment.getEndTime().getTime() - equipment.getStartTime().getTime();

        // 将时间差转换为年、月、日、时、分、秒
        long seconds = timeDifference / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;
        long years = days / 365;

        // 计算剩余的部分
        long remainingDays = days % 365;
        long remainingMonths = remainingDays / 30;
        long remainingDaysAfterMonths = remainingDays % 30;
        long remainingHours = hours % 24;
        long remainingMinutes = minutes % 60;
        long remainingSeconds = seconds % 60;

        // 构建格式化的字符串
        StringBuilder formattedTime = new StringBuilder();
        formattedTime.append(String.format("%04d", years)).append("/")
                .append(String.format("%02d", remainingMonths)).append("/")
                .append(String.format("%02d", remainingDaysAfterMonths)).append("/")
                .append(String.format("%02d", remainingHours)).append("/")
                .append(String.format("%02d", remainingMinutes)).append("/")
                .append(String.format("%02d", remainingSeconds));

        // 如果 runtime 不为空，则将其加上去
        if (equipment.getTotalRuntime() != null && !equipment.getTotalRuntime().isEmpty()) {
            try {
                // 解析现有的 runtime
                String[] parts = equipment.getTotalRuntime().split("/");
                long existingYears = Long.parseLong(parts[0]);
                long existingMonths = Long.parseLong(parts[1]);
                long existingDays = Long.parseLong(parts[2]);
                long existingHours = Long.parseLong(parts[3]);
                long existingMinutes = Long.parseLong(parts[4]);
                long existingSeconds = Long.parseLong(parts[5]);

                // 将现有时间和新时间相加
                long totalSeconds = remainingSeconds + existingSeconds;
                long totalMinutes = remainingMinutes + existingMinutes + (totalSeconds / 60);
                long totalHours = remainingHours + existingHours + (totalMinutes / 60);
                long totalDays = remainingDaysAfterMonths + existingDays + (totalHours / 24);
                long totalMonths = remainingMonths + existingMonths + (totalDays / 30);
                long totalYears = years + existingYears + (totalMonths / 12);

                // 计算剩余的部分
                long finalSeconds = totalSeconds % 60;
                long finalMinutes = totalMinutes % 60;
                long finalHours = totalHours % 24;
                long finalDays = totalDays % 30;
                long finalMonths = totalMonths % 12;

                // 构建最终的格式化字符串
                formattedTime = new StringBuilder();
                formattedTime.append(String.format("%04d", totalYears)).append("/")
                        .append(String.format("%02d", finalMonths)).append("/")
                        .append(String.format("%02d", finalDays)).append("/")
                        .append(String.format("%02d", finalHours)).append("/")
                        .append(String.format("%02d", finalMinutes)).append("/")
                        .append(String.format("%02d", finalSeconds));
            } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
                // 如果解析失败，返回原始的 formattedTime
            }
        }
        equipment.setTotalRuntime(formattedTime.toString());
    }
}